<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\api\model\Collage\CollageModel;
use app\api\model\Goods\GoodsModel;
use app\api\model\Order\OrderGoodsModel;
use app\api\model\Order\OrderModel;
use app\api\model\User\UserModel;
use app\api\model\User\UserVerifyCodeModel;
use app\Request;
use app\Utils\AliDaYuSMS;
use app\Utils\ImageUtil;
use app\Utils\StrUtil;
use app\Utils\Util;
use think\Exception;
use think\facade\Db;
use think\facade\View;

class Index extends BaseController
{
    /**
     * 邀请H5
     * @param Request $request
     * @return string
     */
    public function invite(Request $request)
    {
        $param = $request->param();
        if(!empty($param['invite'])){
            $parent = UserModel::getUserWhere([['invite_code','=',$param['invite']]]);
        }
        View::assign(["invite"=>!empty($param["invite"]) ? $param["invite"] : ""]);
        return View::fetch('./invite');
    }

    /**
     * @api {post} /get_sms_verify_code 获取短信验证码
     * @apiGroup 系统
     * @apiParam {string} mobile 手机号
     * @apiParam {int} type 类型 1：注册 2：忘记密码
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getSMSVerifyCode(Request $request)
    {
        $param = $request->param();
        $mobile = !empty($param['mobile']) ? $param['mobile'] : "";
        $type = !empty($param['type']) ? $param['type'] : "";

        if($type == 1){
            $user = UserModel::getUserWhere([['account','=',$param['mobile']]]);
            if(!empty($user)){
                return Util::returnJson(self::CODE_ERROR,null,"手机号已注册");
            }
        }

        if($type == 2){
            $user = UserModel::getUserWhere([['account','=',$param['mobile']]]);
            if(empty($user)){
                return Util::returnJson(self::CODE_ERROR,null,"手机号未注册");
            }
        }


        $code = UserVerifyCodeModel::getUserVerifyCodeWhere([['mobile','=',$mobile],['type','=',$type],['status','=',0]]);
        if(!empty($code)){
            $time = strtotime($code['add_time'])+$code['time'];
            if($time > time()){
                return Util::returnJson(self::CODE_ERROR,null,"验证码未过期，请不要重复申请");
            }
        }
        $verify_code = Util::randomCode(6);
        $data_code = [
            'mobile'=>$mobile,
            'type'=>$type,
            'code'=>$verify_code,
            'time'=>600,
            'status'=>0,
            'up_time'=>date("Y-m-d H:i:s",time()),
            'add_time'=>date("Y-m-d H:i:s",time())
        ];
        Db::startTrans();
        try{
            //发送验证码
            $data = AliDaYuSMS::i()->sendSMS($mobile,$verify_code,$type);
            if($data['code'] == 0){
                $id = UserVerifyCodeModel::addUserVerifyCode($data_code);
                if($id){
                    Db::commit();
                    return Util::returnJson(self::CODE_SUCCESS,null,"发送成功");
                }else{
                    Db::rollback();
                    return Util::returnJson(self::CODE_ERROR,null,"获取失败2");
                }
            }else{
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR,null,"获取失败1");
            }
        }catch (Exception $e){
            Db::rollback();
            return Util::returnJson(self::CODE_ERROR,null,"获取失败3");
        }
    }

    /**
     * @api {get} /get_app_version APP版本
     * @apiGroup 系统
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getAppVersion(Request $request)
    {
        $data['url'] = ImageUtil::i()->replaceUrl($this->setting['app_url']);
        $data['version'] = $this->setting['app_version'];
        $data['version_name'] = !empty($this->setting['version_name']) ? $this->setting['version_name'] : "";
        return Util::returnJson(self::CODE_SUCCESS,$data);
    }

    /**
     * 测试创建订单拼团
     * @param Request $request
     * @return array
     */
    public function testCollage(Request $request)
    {
        $param = $request->request();
        //新增团
        $order_goods = OrderGoodsModel::getOrderGoodsWhere([['order_id','=',$param['order_id']]]);
        $collage_sn =  StrUtil::i()->getOrderSn(2);
        $time = date("Y-m-d H:i:s",time());
        $end_time = date('Y-m-d H:i:s',strtotime($time)+86400);
        $goodsInfo =  GoodsModel::getGoodsWhere([['id','=',$order_goods['goods_id']]]);
        $collage_data = [
            'collage_sn'=>$collage_sn,
            'uid'=>1,
            'goods_id'=>$goodsInfo['id'],
            'collage_count'=>$goodsInfo['group_num'],
            'now_count'=>1,
            'up_time'=>$time,
            'add_time'=>$time,
            'mer_id'=>$goodsInfo['mer_id'],
            'start_time'=>$time,
            'end_time'=>$end_time,
            'goods_info'=>json_encode($goodsInfo)
        ];

        if(1 >= $goodsInfo['group_num']){
            $collage_data['status'] = 1;
        }else{
            $collage_data['status'] = 0;
        }

        $collage_id = CollageModel::addCollage($collage_data);
        if(!empty($collage_id)){
            $order_save = [
                'collage_id'=>$collage_id
            ];
            OrderModel::updateOrderWhere([['id','=',$param['order_id']]],$order_save);
        }
        return Util::returnJson(self::CODE_SUCCESS,null,"创建成功");
    }


    /**
     * 测试付款回调
     * @param Request $request
     * @return array
     */
    public function testNotify(Request $request)
    {
        $order_sn = "MF_2020090810242230373";
        $trade_no = "2020090810501950083";
        $pay_amount = 129;
        $flag = WxNotify::payLogic($order_sn,$trade_no,$pay_amount);
        return Util::returnJson(self::CODE_SUCCESS,$flag);
    }

    /**
     * 测试数据
     */
    public function testData()
    {
        $data = urldecode('%5B%22%7B%5C%22goods_id%5C%22%3A6%2C%5C%22number%5C%22%3A1%2C%5C%22unique%5C%22%3A%5C%2265f58ee2ead900%5C%22%7D%22%5D');
        $data = json_decode($data);
        var_dump($data);
        $list = [];
        foreach ($data as $item){
            $var = json_decode($item, true);
            array_push($list,$var);
        }
        var_dump($list);
    }

}
